package httplib

import (
	"bytes"
	"encoding/json"
	"io/ioutil"
	"log"
	"net/http"
	"net/url"
)

type MyRequest struct {
	method string
	url    string
	body   []byte
	header map[string]string
	params map[string]string
}

func NewRequest(rawUrl string, method string) *MyRequest {
	u, err := url.Parse(rawUrl)
	if err != nil {
		log.Println("httplib error", err)
	}
	return &MyRequest{method: method, url: u.String()}
}

func Get(rawUUrl string) *MyRequest {
	return NewRequest(rawUUrl, "GET")
}

func Post(rawUUrl string) *MyRequest {
	return NewRequest(rawUUrl, "POST")
}

func (r *MyRequest) Body(body string) *MyRequest {
	r.body = str2bytes(body)
	return r
}

func (r *MyRequest) BodyBytes(bodyBytes []byte) *MyRequest {
	r.body = bodyBytes
	return r
}

func (r *MyRequest) Params(params map[string]string) *MyRequest {
	r.params = params
	return r
}

func (r *MyRequest) Header(header map[string]string) *MyRequest {
	r.header = header
	return r
}

func (r *MyRequest) SendRequest() ([]byte, error) {
	if len(r.params) != 0 {
		r.url += "?"
		for k, v := range r.params {
			r.url += k + "=" + v
		}
	}
	req, err := http.NewRequest(r.method, r.url, bytes.NewReader(r.body))
	if err != nil {
		return nil, err
	}

	if len(r.header) != 0 {
		for k, v := range r.header {
			req.Header.Add(k, v)
		}
	}

	client := new(http.Client)
	resp, err := client.Do(req)
	if err != nil {
		return nil, err
	}
	return ioutil.ReadAll(resp.Body)
}

func (r *MyRequest) Bytes() ([]byte, error) {
	return r.SendRequest()
}

func (r *MyRequest) String() (string, error) {
	respBytes, err := r.SendRequest()
	return bytes2str(respBytes), err
}

func (r *MyRequest) Json(v interface{}) error {
	respBytes, err := r.SendRequest()
	if err != nil {
		return err
	}
	return json.Unmarshal(respBytes, v)
}
